package mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqServer {

    public static void main(String[] args) {

        String broker = "tcp://broker.emqx.io:1883";
        String topic = "asdfsdfa";
        String clientid = "subscribe_client";

        int qos = 0;



        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            // 设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    System.err.println("丢包："+ throwable.getMessage());
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    System.err.println("topic"+s);
                    System.err.println("qos"+mqttMessage.getQos());
                    System.err.println("content"+ new String(mqttMessage.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    System.err.println("complete"+ iMqttDeliveryToken.isComplete());
                }
            });
            //连接
            client.connect(options);
            client.subscribe(topic,qos);

        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

}
